A = imread('cameraman.tif');
B = imnoise(A,'salt & pepper',0.04);
[row,col] = size(A);
figure, imshow(A);
figure, imshow(B);
C = padarray(A,[1,1]);
weightmatrix = [1 1 1; 1 2 1; 1 1 1];
reshapematrix = reshape(weightmatrix,[1,9]);
disp(reshapematrix);
sum = 0;
for i = 1:9
    sum = sum + reshapematrix(i);
end
disp(sum);
%declare the new single dimension matrix for sorting 
sortarray(1:1,1:100) = 999;
for  i = 2: (row-1)
   for j = 2 : (row-1) 
       arrayIndex = 1;
       for k = 1 : 3
           for l = 1 : 3
               currentweight = weightmatrix(k,l);
               for i1 = 1:currentweight
                   sortarray(1,arrayIndex) = C((i-2)+k,(j-2)+l) ;
                   arrayIndex = arrayIndex + 1;
               end
           end
       end
       %sort the matrix
       for m = 1 : sum
           for n = 1 : sum-1
              if(sortarray(n) > sortarray(n+1))
                  temp = sortarray(n);
                  sortarray(n) = sortarray(n+1);
                  sortarray(n+1) = temp;
              end
           end
       end
       C(i,j) = median(sortarray(1:sum));
end
end
figure,imshow(C);